﻿#!/usr/bin/python
#-*-coding:utf-8-*-

#socket server端
#获取socket构造及常量
from socket import *
import os
#''代表服务器为localhost
myHost = ''
#在一个非保留端口号上进行监听
myPort = 50009
#设置一个TCP socket对象
sockobj = socket(AF_INET, SOCK_STREAM)
#绑定它至端口号
sockobj.bind((myHost, myPort))
#监听，允许1个连结
sockobj.listen(1)
pathPrefix='Z:/mt6580_new/'
pathStart = 'path:'
privatePathStart = 'ppath:'
commandStart = "command:"
resultPrefix = "result:"
pathSplit = '/'
fileNotFind = 'No such file'
errorNoFile = 'ERROR: PHONE: NO such file OR device not online :'
remountSuccess = 'remount succeeded'
pushSuccess = 'bytes'


def getRealPath(path, length):
	split=path.split(pathSplit)
	start=0
	for s in split[:len(split)-length]:
		start=len(s)+1+start
	return path[start:]

def checkFileAtPhone(filePath):
	if (os.system('adb shell ls') == 0):
		result=os.popen('adb shell ls '+filePath).readlines()
		if (result[0].find(fileNotFind) >= 0):
			return False
		return True
	return False

def killProgress(pregressName):
	print "yadong debug", pregressName
	print "adb shell ps | grep -i " + pregressName + " | awk '{print $2}' | xargs adb shell kill -9"
	os.system('adb shell ps | grep -i ' + pregressName + " | awk '{print $2}' | xargs adb shell kill -9")

#直到进程结束时才结束循环
while True:
    #等待下一个客户端连结
    connection, address = sockobj.accept( )
    #连结是一个新的socket
    print 'Server connected by', address
    while True:
		#读取客户端套接字的下一行
		data = connection.recv(1024)
		#如果没有数量的话，那么跳出循环
		if not data:break
		print 'GetMessage', data
		if (data.find("exit") == 0):
			break;
		if (data.find(pathStart) == 0 or data.find(privatePathStart) == 0):
			if (data.find(pathStart) == 0):
				path=data[len(pathStart):]
				length=3
			else:
				path=data[len(privatePathStart):]
				length=4
			print 'GetPath', path
			split=path.split(pathSplit)
			if (len(split) < length):
				print 'Path error'
			else:
				realPath=getRealPath(path, length)
				print realPath
				result=os.popen('adb remount&&adb push '+pathPrefix+path+' ' + realPath).readlines()
				for r in result:
					connection.send(resultPrefix + r)
				split2=realPath.split(pathSplit)
				appName=split2[len(split2) - 1].split(".")[0]
				killProgress(appName)
		#发送一个回复至客户端
		if (data.find(commandStart) == 0):
			command=data[len(commandStart):]
			result=os.popen(command).readlines()
			for r in result:
				connection.send(resultPrefix + r);
		connection.send('Echo=>' + data)
		break
	#当socket关闭时eof
    connection.close( )
